import {createReducer} from 'redux-act';
import u from 'updeep';
import {createAction2} from '../util';
import {bed, up, nullKey, dataKey} from '../util/bed';
import * as ajax from '../util/ajax';
import * as http from '../util/http';
const name = 'module';
const [
    load,
    create,
    modify
] = [
    `${name}_load`,
    `${name}_create`,
    `${name}_modify`
].map(createAction2);

export const actions = {
    load: (q = {}) => bed(ajax.get(http.makeUrl(`/${name}`, q)), load),
    create: (data) => bed(ajax.post(`/${name}`, data), create, {data}),
    modify: (data) => bed(ajax.put(`/${name}`, data), modify, {data})
};
/**
 * NOTE:由于antd treesselect中需要id是字符串,获取和新建是转换保持一致
 */
export default createReducer({
    [load]: (state, payload) => {
        let result = up(state, payload);
        let {data} = payload;
        if (data) {
            data = u.updateIn('*.Id', i => i + '', data);
            data = u.updateIn('*.Pid', i => (i === null ? i : i + ''), data);
            result = u({[dataKey]: data}, result);
        }
        return result;
    },
    [create]: (state, payload, {data}) => {
        let result = up(state, payload, nullKey);
        const {data: Id} = payload;
        if (Id) {
            data.Id = Id + '';//转为字符串
            result = u({[dataKey]: (arr) => [].concat(arr || [], [data])}, result);
        }
        return result;
    },
    [modify]: (state, payload, {data, done}) => {
        let result = up(state, payload);
        if (done) {
            result = u({[dataKey]: u.map(d => (d.Id === data.Id ? data : d))}, result);
        }
        return result;
    }
}, {});
